package com.geeyuu.android.activity;

import java.io.File;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

import com.geeyuu.android.GeeConstants;
import com.geeyuu.android.GeePrefrence;
import com.geeyuu.android.R;
import com.geeyuu.android.model.BaseUserInfo;
import com.geeyuu.android.service.DataKey;
import com.geeyuu.android.service.ProtocolCommand;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.CommonUtil;
import com.geeyuu.android.utils.ImageLoder;
import com.geeyuu.android.utils.LogUtil;

public class PhotoBrowserActivity extends BaseActivity {
    
    public static boolean isNeedRefresh = false;

    private int width;
    private long uid;
    private int allStartIndex;
    
    private int pubCount = 0;
    private int priCount = 0;
    
    private ArrayList<String> allPhotoIds;
    
    private ImageLoder imageLoder;
    private Boolean isStarting = true;
    private int currentIndex = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.TAG = "PhotoBrowserActivity_" + CommonUtil.getRandomStr();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_browser_layout);
        
        Intent intent = getIntent();
        int index = intent.getIntExtra("index", -1);
        int type = intent.getIntExtra("type", -1);
        uid = intent.getLongExtra("uid", -1l);
        
        String[] pub = intent.getStringArrayExtra("publicPhotoIds");
        String[] pri = intent.getStringArrayExtra("privatePhotoIds");
        
        if(type == 2 && (pri == null || pri.length == 0)){
            LogUtil.e(TAG, "点击了私照，但是私照没有传过来");
            finish();
            return;
        }
        
        if(null == pub && null == pri){
            finish();
            return;
        }
        if(index == -1 || type == -1 || uid == -1l){
            finish();
            return;
        }
        
        allPhotoIds = new ArrayList<String>();
        
        if(null != pub){
            pubCount = pub.length;
            for(String str : pub){
                allPhotoIds.add(str);
            }
        }
        if(null != pri){
            priCount = pri.length;
            for(String str : pri){
                allPhotoIds.add(str);
            }
        }
        
        if(type == 0){
            allStartIndex = index;
        }else if(type == 1){
            allStartIndex = index + pubCount;
        }else{
            finish();
            return;
        }
        
        imageLoder = new ImageLoder(getApplicationContext());
        
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        width = displayMetrics.widthPixels;
        
        initContentViews();
        
        startBindService();

    }
    
    private BaseAdapter photoAdapter;
    private Gallery gallery;
    private TextView photoIndexTextView;
    
    private void initContentViews() {
        findViewById(R.id.back).setOnClickListener(mOnClickListener);
        
        photoIndexTextView = (TextView)findViewById(R.id.photo_index);
        gallery = (Gallery)findViewById(R.id.gallery);
        gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentIndex = position;
                if(position < pubCount){
                    photoIndexTextView.setText("公开相册 " + (position + 1) + "/" + pubCount);
                }else{
                    photoIndexTextView.setText("私密相册 " + (position + 1 - pubCount) + "/" + priCount);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        
        photoAdapter = new PhotoAdapter();
        gallery.setAdapter(photoAdapter);
        gallery.setSelection(allStartIndex);
        gallery.setSpacing(10);
        
        if(uid == GeePrefrence.getMyUid(getApplicationContext())){
            findViewById(R.id.my_photo_menu).setVisibility(View.VISIBLE);
            findViewById(R.id.set_to_avatar).setOnClickListener(mOnClickListener);
            findViewById(R.id.delete_photo).setOnClickListener(mOnClickListener);
        }else{
            findViewById(R.id.bottom_menu_container).setVisibility(View.GONE);
        }
    }
    
    String deletePhotoId;
    String currentPhotoId;
    
    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if(R.id.set_to_avatar == id){
                
                currentPhotoId = allPhotoIds.get(currentIndex);
                if(GeePrefrence.getMyMainPhotoId(getApplicationContext()).equals(currentPhotoId)){
                    AndroidUtil.showMyToast(getApplicationContext(), "已经是头像了");
                    return;
                }
                
                showProgressDialog("设置头像", "正在设置头像，请稍等..", true);
                Bundle bundle = new Bundle();
                bundle.putString(DataKey.S_KEY_USERINFO_MAIN_PHOTO_ID, currentPhotoId);
                sendMsgToService(ProtocolCommand.CMD_SET_MY_USER_INFO, bundle);
                
            }else if(R.id.delete_photo == id){
                
                deletePhotoId = allPhotoIds.get(currentIndex);
                if(GeePrefrence.getMyMainPhotoId(getApplicationContext()).equals(deletePhotoId)){
                    AndroidUtil.showMyToast(getApplicationContext(), "头像不可删除哦~");
                    return;
                }
                showProgressDialog("删除照片", "正在删除照片，请稍等..", true);
                Bundle bundle = new Bundle();
                if(currentIndex < pubCount){
                    bundle.putString(DataKey.S_KEY_PHOTO_TYPE, DataKey.S_VALUE_USER_PHOTO_TYPE_PUBLIC);
                }else{
                    bundle.putString(DataKey.S_KEY_PHOTO_TYPE, DataKey.S_VALUE_USER_PHOTO_TYPE_PRIVATE);
                }
                bundle.putString(DataKey.S_KEY_PHOTO_ACTION, DataKey.S_VALUE_ACTION_DELETE);
                bundle.putString(DataKey.S_KEY_PHOTO_ID, deletePhotoId);
                sendMsgToService(ProtocolCommand.CMD_ADD_TO_ALBUM, bundle);
                
            }else if(R.id.back == id){
                finish();
            }
        }
    };

    @Override
    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal) {
        switch (cmd) {
        case ProtocolCommand.CMD_SET_MY_USER_INFO:
            if(isMsgNormal){
                isNeedRefresh = true;
                GeePrefrence.setMyMainPhotoId(getApplicationContext(), currentPhotoId);
                ContentValues cv2 = new ContentValues();
                cv2.put("uid", uid);
                cv2.put(BaseUserInfo.EXTRA_MAIN_PHOTO_ID, currentPhotoId);
                BaseUserInfo.saveOrUpdateUserInfo(getApplicationContext(), cv2);
                AndroidUtil.showMyToast(getApplicationContext(), "设置头像成功");
            }else{
                AndroidUtil.showMyToast(getApplicationContext(), "设置头像失败，请重试");
            }
            break;
        
        case ProtocolCommand.CMD_ADD_TO_ALBUM:
            if(isMsgNormal){
                isNeedRefresh = true;
                String photoIds = null;
                if(currentIndex < pubCount){
                    photoIds = BaseUserInfo.getUserInfoSingleStrColumn(getApplicationContext(), uid, BaseUserInfo.EXTRA_PUBLIC_PHOTO_IDS);
                }else{
                    photoIds = BaseUserInfo.getUserInfoSingleStrColumn(getApplicationContext(), uid, BaseUserInfo.EXTRA_PRIVATE_PHOTO_IDS);
                }
                if(null != photoIds && photoIds.contains(deletePhotoId)){
                    String[] photoIdArray = photoIds.split(",");
                    if(null != photoIdArray && photoIdArray.length > 0){
                        StringBuilder sb = new StringBuilder();
                        int length = photoIdArray.length;
                        for(int i=0; i<length; i++){
                            String pId = photoIdArray[i];
                            if(!pId.equals(deletePhotoId)){
                                sb.append(pId + ",");
                            }
                        }
                        ContentValues cv = new ContentValues();
                        cv.put("uid", uid);
                        if(sb.length() > 0){
                            sb.deleteCharAt(sb.length() - 1);
                            photoIds = sb.toString();
                        }else{
                            photoIds = "";
                        }
                        if(currentIndex < pubCount){
                            cv.put(BaseUserInfo.EXTRA_PUBLIC_PHOTO_IDS, photoIds);
                        }else{
                            cv.put(BaseUserInfo.EXTRA_PRIVATE_PHOTO_IDS, photoIds);
                        }
                        BaseUserInfo.updateUserInfo(getApplicationContext(), cv);
                        
                        File deleteFile = new File(GeeConstants.PATH_SMALL_IMAGE_FOLDER, deletePhotoId);
                        deleteFile.delete();
                        deleteFile = new File(GeeConstants.PATH_LARGE_IMAGE_FOLDER, deletePhotoId);
                        deleteFile.delete();
                        
                        if(currentIndex < pubCount){ //pub
                            pubCount--;
                        }else{ //pri
                            priCount--;
                        }
                        
                        if((pubCount + priCount) <= 0){
                            finish();
                            return;
                        }
                        
                        allPhotoIds.remove(currentIndex);
                        photoAdapter.notifyDataSetChanged();
                        
                        int nowCurrentIndex = currentIndex - 1;
                        if(nowCurrentIndex < 0){
                            nowCurrentIndex = 0;
                        }
                        gallery.setSelection(nowCurrentIndex);
                        
                        if(nowCurrentIndex < pubCount){
                            photoIndexTextView.setText("公开相册 " + (nowCurrentIndex + 1) + "/" + pubCount);
                        }else{
                            photoIndexTextView.setText("私密相册 " + (nowCurrentIndex + 1 - pubCount) + "/" + priCount);
                        }
                    }else{
                        LogUtil.e(TAG, "photoIdArray is null or length is 0");
                    }
                }else{
                    LogUtil.e(TAG, "需要删除的照片id数据库没有记录");
                }
                
            }else{
                AndroidUtil.showMyToast(getApplicationContext(), "删除照片失败");
            }
            break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isStarting = false;
            }
        }, 200);
    }
    
    class PhotoAdapter extends BaseAdapter{
        
        private int count;
        private boolean flag = true;
        
        public PhotoAdapter(){
            count = allPhotoIds.size();
            LogUtil.d(TAG, "adapter count: " + count);
        }
        @Override
        public int getCount() {
            return count;
        }
        @Override
        public void notifyDataSetChanged() {
            count = allPhotoIds.size();
            super.notifyDataSetChanged();
        }
        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            
            System.out.println(position);
            
            View view = convertView;
            ImageView imageView = null;
            if(null == view){
                view = getLayoutInflater().inflate(R.layout.gallery_item, parent, false);
                ViewGroup.LayoutParams vl = view.getLayoutParams();
                if(vl == null){
                    vl = new ViewGroup.LayoutParams(width, width);
                }else{
                    vl.width = width;
                    vl.height = width;
                }
                view.setLayoutParams(vl);
            }
            imageView = (ImageView)view.findViewById(R.id.photo_image_view);
            if(isStarting){
                if(flag){
                    flag = false;
                    imageLoder.add(allPhotoIds.get(position), imageView, false);
                }
            }else{
                imageLoder.add(allPhotoIds.get(position), imageView, false);
            }
            return view;
        }
        
    }
    
    @Override
    protected void onDestroy() {
        stopBindService();
        if(null != imageLoder){
            imageLoder.destory();
        }
        super.onDestroy();
    }

}
